#include "stdafx.h"

void toLua()
{
	using luabind::def;
	using luabind::class_;

	luabind::module(lua::State())
	[
		class_<D3DXVECTOR3>("Vector3").
		def(luabind::constructor<float, float, float>()).
		def_readwrite("X", &D3DXVECTOR3::x).
		def_readwrite("Y", &D3DXVECTOR3::y).
		def_readwrite("Z", &D3DXVECTOR3::z),
		
		class_<D3DXVECTOR2>("Vector2").
		def(luabind::constructor<float, float>()).
		def_readwrite("X", &D3DXVECTOR2::x).
		def_readwrite("Y", &D3DXVECTOR2::y),

		class_<D3DXCOLOR>("Color").
		def(luabind::constructor<float, float, float, float>()).
		def_readwrite("R", &D3DXCOLOR::r).
		def_readwrite("G", &D3DXCOLOR::g).
		def_readwrite("B", &D3DXCOLOR::b).
		def_readwrite("A", &D3DXCOLOR::a),

		class_<POINT>("Point").
		def(luabind::constructor<>()).
		def_readwrite("X", &POINT::x).
		def_readwrite("Y", &POINT::y)
	];
}



int WINAPI WinMain(	HINSTANCE hInstance,
					HINSTANCE hPrevInstance,
					LPSTR     lpCmdLine,
					int       nCmdShow )
{
	lua::Create();
	AllocConsole();
	
	luabind::open(lua::State());
	luaL_openlibs(lua::State());

	globals::hInstance = hInstance;
	D3DXVECTOR3 vec;

	try
	{
		toLua();
		Camera::toLua();
		ParticleEmitter::toLua();
		ParticleSystem::toLua();
		Plane::toLua();
		StaticMesh::toLua();
		DynamicMesh::toLua();
		Game game;

		if(luaL_dofile(lua::State(), "game\\Main.lua") != 0)
			throw std::exception();
		game.toLua();
		luabind::call_function<void>(lua::State(), "main", lpCmdLine);
	}
	catch(std::exception /*&e*/)
	{
		auto lastError = lua_tostring(lua::State(), -1);
		std::cerr << "Error: " << lastError << std::endl;
		std::ofstream file("errors.txt", std::ios::out|std::ios::app);
		if(file.is_open())
			file << "Error: " << lastError << std::endl;
	}
	catch(...)
	{
		std::cerr << "Unexpected Error!" << std::endl;
	}

	lua::Close();

	return 0;
}